package admin

import (
	"invitation/internal/application"
	"invitation/internal/http/middleware"
	"invitation/internal/pojo/dto"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

func DeleteTeacherEndpoint(app *application.Application) func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		teacherReq := ctx.Locals(middleware.LocalKeysTeacherCreateRequest).(*dto.FirstTimePayload)
		log.Debug().Msgf("delete: teacherReq:%v", teacherReq)
		if teacherReq.TeacherID == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "teacher_id is required",
			})
		}
		txCtx, err := app.RepoManager().BeginTx(ctx.Context())
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		defer func() {
			if err != nil {
				app.RepoManager().RollbackTx(txCtx)
			} else {
				app.RepoManager().CommitTx(txCtx)
			}
		}()
		oldTeacherInfo, err := app.RepoManager().FirstTimeTeacherInfoRepo().FindOneByTeacherID(teacherReq.TeacherID)
		log.Debug().Msgf("oldTeacherInfo:%v", oldTeacherInfo)
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		if err := app.RepoManager().FirstTimeTeacherInfoRepo().Delete(oldTeacherInfo.ID); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		if err := app.RepoManager().FirstTimePostportRepo().Delete(oldTeacherInfo.ID); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		return ctx.Status(200).JSON(fiber.Map{
			"message": "success",
		})
	}
}
